﻿/// <summary>
/// Developer: CHOOI KAH WAI
/// Last Modified: 15/11/2009
/// </summary>

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ARSS.Client;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Xml;
using System.Windows.Threading;
using ARSS.Common;


namespace ARSS.Visual
{
	/// <summary>
	/// Interaction logic for ConnectingDialog.xaml
	/// </summary>
	public partial class ConnectingDialog : Window
    {
        #region Properties

        /// <summary>
        /// Server ip
        /// </summary>
        public string ServerIPAddress { get; set; }

        /// <summary>
        /// Server listening port
        /// </summary>
        public int ServerPort { get; set; }

        #endregion

        #region Functions

        /// <summary>
        /// Constructor
        /// </summary>
        public ConnectingDialog()
		{
			this.InitializeComponent();
			
			// Insert code required on object creation below this point.
            this.Loaded += new RoutedEventHandler(ConnectingDialog_Loaded);
            this.Closing += new System.ComponentModel.CancelEventHandler(ConnectingDialog_Closing);
		}

        /// <summary>
        /// Dialog closing event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ConnectingDialog_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Core.Instance.MyData.ClientDisconnected -= new ClientData.ClientDisconnectedHandler(OnClientDisconnected);
        }

        /// <summary>
        /// Dialog loaded event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ConnectingDialog_Loaded(object sender, RoutedEventArgs e)
        {
            //Connect to server here
            Core.Instance.MyData.TCPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            SocketAsyncEventArgs evt = new SocketAsyncEventArgs();
            evt.Completed += new EventHandler<SocketAsyncEventArgs>(Connected);
            evt.UserToken = Core.Instance.MyData.TCPSocket;
            evt.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(ServerIPAddress), ServerPort);
            Core.Instance.MyData.TCPSocket.ConnectAsync(evt);

            Core.Instance.MyData.ClientDisconnected += new ClientData.ClientDisconnectedHandler(OnClientDisconnected);
            
        }

        /// <summary>
        /// Client disconnected event handler
        /// </summary>
        /// <param name="sender"></param>
        protected void OnClientDisconnected(ClientData sender)
        {
            this.Dispatcher.Invoke((Action)delegate
            {
                StatusTextBlock.Text = "Connection failed.";
            }, null);
        }

        /// <summary>
        /// Connection completed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Connected(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                this.Dispatcher.Invoke((Action)delegate
                {
                    StatusTextBlock.Text = "Connected.Synchronizing data...";
                },null);

                // Send nickname to server first
                MemoryStream ms = new MemoryStream();
                // Action code
                ms.Write(BitConverter.GetBytes((int)NetworkActionCodesEnum.UserNickname), 0, 4);
                // Nickname length
                byte[] nameBuffer = System.Text.ASCIIEncoding.UTF8.GetBytes(Core.Instance.MyData.Name);
                ms.Write(BitConverter.GetBytes(nameBuffer.Length), 0, 4);
                // Nickname data
                ms.Write(nameBuffer, 0, nameBuffer.Length);

                Core.Instance.MyData.SendData(ms.GetBuffer(), 8 + nameBuffer.Length);

                Core.Instance.MyData.ReceiveData();
                Core.Instance.MyData.DataReceived += new ClientData.DataReceivedHandler(OnDataReceived);
            }
            else
            {
                this.Dispatcher.Invoke((Action)delegate
                {
                    StatusTextBlock.Text = "Connection failed.";
                }, null);
            }

        }

        /// <summary>
        /// Data received event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        protected void OnDataReceived(ClientData sender, byte[] data)
        {
            // Process data
            MemoryStream buffer = new MemoryStream(data);

            byte[] intBuffer = new byte[4];
            buffer.Read(intBuffer, 0, 4);

            int actionCode = BitConverter.ToInt32(intBuffer, 0);
            switch (actionCode)
            {
                case (int)NetworkActionCodesEnum.SendSceneData:
                    {
                        buffer.Read(intBuffer, 0, 4);
                        int length = BitConverter.ToInt32(intBuffer, 0);
                        byte[] sceneDataBuffer = new byte[length];
                        buffer.Read(sceneDataBuffer, 0, length);
                        XmlReader sceneDataReader = XmlReader.Create(new MemoryStream(sceneDataBuffer));
                        Core.Instance.SceneData.LoadScene(sceneDataReader);

                        // Data synchronized
                        this.Dispatcher.Invoke((Action)delegate
                        {
                            StatusTextBlock.Text = "Data synchronized. Waiting for host to start session...";
                        }, null);
                    }
                    break;
                case (int)NetworkActionCodesEnum.StartSession:

                    this.Dispatcher.Invoke((Action)delegate
                        {
                            if(this.DialogResult == null)
                                this.DialogResult = true;
                        }, null);

                    break;
            }
        }

        /// <summary>
        /// Cancel button clicked event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CancelButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	this.DialogResult = false;

            Core.Instance.MyData.TCPSocket.Close();
        }

        #endregion

    }
}